package org.hxzon.tapestry5.mixins;

//https://github.com/tawus/tawus/tree/f58155264e87c5d18e46c549329d2c967d635fab/tawus-addons
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.internal.util.CaptureResultCallback;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.javascript.InitializationPriority;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.hxzon.tapestry5.util.TapestryEx;

@Import(library = "ZoneRefresh.js")
public class ZoneRefresh {
    /**
     *  Period is seconds 
     */
    @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
    private int period;

    /**
     * Context passed to the event
     */
    @Parameter
    private Object[] context;

    @InjectContainer
    private Zone zone;

    @Inject
    private JavaScriptSupport javaScriptSupport;

    @Inject
    private ComponentResources resources;

    public ZoneRefresh() {
    }

    //For testing purpose
    ZoneRefresh(Object[] context, ComponentResources resources, JavaScriptSupport javaScriptSupport, Zone zone) {
        this.context = context;
        this.resources = resources;
        this.javaScriptSupport = javaScriptSupport;
        this.zone = zone;
    }

    @AfterRender
    void addJavaScript() {
        JSONObject params = new JSONObject();

        params.put("period", period);
        params.put("id", zone.getClientId());
        params.put("URL", createEventLink());

        javaScriptSupport.addInitializerCall(InitializationPriority.LATE, TapestryEx.Event_ZoneRefresh, params);
    }

    private Object createEventLink() {
        Link link = resources.createEventLink(TapestryEx.Event_ZoneRefresh, context);
        return link.toAbsoluteURI();
    }

    Object onZoneRefresh() {
        CaptureResultCallback<Object> callback = new CaptureResultCallback<Object>();
        resources.triggerEvent(TapestryEx.Event_Refresh, context, callback);

        if (callback.getResult() != null) {
            return callback.getResult();
        }
        return zone;
    }

}
